package com.winning.cqs.pregnantbabycare_cqs_v1.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import android.R.integer;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import cn.com.contec.jar.wt100.WTDeviceDataJar;

import com.contec.jar.contec08a.DeviceData;
import com.google.gson.Gson;
import com.winning.cqs.pregnantbabycare_cqs_v1.R;
import com.winning.cqs.pregnantbabycare_cqs_v1.adapter.BlueChoseAdaoter;
import com.winning.cqs.pregnantbabycare_cqs_v1.db.BloodBuf;
import com.winning.cqs.pregnantbabycare_cqs_v1.db.CallBack;
import com.winning.cqs.pregnantbabycare_cqs_v1.db.Helper;
import com.winning.cqs.pregnantbabycare_cqs_v1.db.ICallBack;
import com.winning.cqs.pregnantbabycare_cqs_v1.db.MtBuf;
import com.winning.cqs.pregnantbabycare_cqs_v1.db.SugarBuf;
import com.winning.cqs.pregnantbabycare_cqs_v1.domain.BlueTooth;
import com.winning.cqs.pregnantbabycare_cqs_v1.entity.bgData;
import com.winning.cqs.pregnantbabycare_cqs_v1.entity.bpData;
import com.winning.cqs.pregnantbabycare_cqs_v1.entity.ketData;
import com.winning.cqs.pregnantbabycare_cqs_v1.entity.tmpData;
import com.winning.cqs.pregnantbabycare_cqs_v1.entity.wtData;
import com.winning.cqs.pregnantbabycare_cqs_v1.view.TitleView;
import com.winning.cqs.pregnantbabycare_cqs_v1.volley.VolleyRunnableService;

public class BlueChoseActivity extends BaseActivity implements ICallBack {
	private BluetoothAdapter btAdapt;
	private BlueChoseAdaoter blueAdapter;
	private List<BlueTooth> list;
	private BluetoothChatService mChatService;
	private SugarChatService sugarChatService;
	private BloodService bloodService;
	public static BluetoothSocket btSocket;
	static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
	private CallBack call;
	public MtBuf m_mtbuf;
	public SugarBuf s_mtbuf;
	public BloodBuf b_mtbuf;
	private LinearLayout lin_tag;
	private ListView listView;
	private bgData bg = new bgData();
	private bpData bp = new bpData();
	private wtData wt = new wtData();
	private tmpData tmp = new tmpData();
	private ketData ket = new ketData();
	private String strDate = null;
	private TextView tv_tag;
	
	private int getWet=0;
	private int getBlood=0;

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		btAdapt.cancelDiscovery();
		if (!(btSocket == null)) {
			try {
				btSocket.close();
				btSocket = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_health_bluetooth);
		TAG = "HealthInputActivity";
		loadView();

		m_mtbuf = new MtBuf();
		s_mtbuf = new SugarBuf();
		b_mtbuf = new BloodBuf();
		call = new CallBack(this.m_mtbuf, s_mtbuf, b_mtbuf, this);

		TitleView.left_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				openProDialog("蓝牙连接关闭中");
				runOnUiThread(new  Runnable() {
					public void run() {						
						
						if (!(btSocket == null)) {
							try {
								mChatService.stop();
								bloodService.stop();
								btSocket.close();
								btSocket = null;
								btAdapt.cancelDiscovery();
								Thread.sleep(2000);
								
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
						//t
						finish();
					}
				});
				
			}
		});
		TitleView.right_edit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				saveMonitor();
			}
		});
		// 注册Receiver来获取蓝牙设备相关的结果
		IntentFilter intent = new IntentFilter();
		intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
		intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(searchDevices, intent);
		tv_tag.setText("请打开需要检测的设备，并靠近手机");
		btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
		if (btAdapt != null) {
			System.out.println("本机拥有蓝牙设备");
			if (!btAdapt.isEnabled()) {
				Intent intent0 = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivity(intent0);
			} else {
				btAdapt.startDiscovery();
				openProDialog("正在搜索中，请稍后");
			}

		}
		list = new ArrayList<BlueTooth>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		strDate = sdf.format(new Date());
		blueAdapter = new BlueChoseAdaoter(context,
				R.layout.item_bluetooth_listview, list);
		listView.setAdapter(blueAdapter);

		if (mChatService == null || sugarChatService == null
				|| bloodService == null)
			setupChat();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			System.out.println(""+(keyCode == KeyEvent.KEYCODE_BREAK));
			openProDialog("蓝牙连接关闭中");
			runOnUiThread(new  Runnable() {
				public void run() {						
					
					if (!(btSocket == null)) {
						try {
							mChatService.stop();
							bloodService.stop();
							btSocket.close();
							btSocket = null;
							btAdapt.cancelDiscovery();
							Thread.sleep(2000);
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					//t
					finish();
				}
			});
		}
		return super.onKeyDown(keyCode, event);
	}

	private void setupChat() {
		// TODO Auto-generated method stub
		mChatService = new BluetoothChatService(context, call);
		sugarChatService = new SugarChatService(context, call);
		bloodService = new BloodService(context, call);
	}

	private void loadView() {
		// TODO Auto-generated method stub
		lin_tag = (LinearLayout) findViewById(R.id.health_bluetooth_lin_tag);
		listView = (ListView) findViewById(R.id.health_bluetooth_list);
		tv_tag = (TextView) findViewById(R.id.health_bluetooth_tv_tag);
	}

	private void saveMonitor() {

		Gson gson = new Gson();
		bp.setHpValue(22);
		bp.setLpValue(22);
		bp.setMode(0);
		bp.setMonitorDate(strDate);
		bp.setPulse(22);
		bp.setUnit("mmHg");
		String bpString = "[" + gson.toJson(bp) + "]";

		bg.setMonitorDate(strDate);
		bg.setMode(0);
		bg.setFood(0);
		bg.setBgValue(22);
		bg.setUnit("mmol/L");
		String bgString = "[" + gson.toJson(bg) + "]";

		wt.setMode(0);
		wt.setMonitorDate(strDate);
		wt.setUnit("Kg");
		wt.setWtValue(22);
		String wtString = "[" + gson.toJson(wt) + "]";

		tmp.setTmpValue(22);
		tmp.setMode(0);
		tmp.setMonitorDate(strDate);
		tmp.setUnit("°C");
		String tmpString = "[" + gson.toJson(tmp) + "]";

		ket.setMonitorDate(strDate);
		ket.setMode(0);
		ket.setUnit("");
		ket.setKetValue(22);
		String ketString = "[" + gson.toJson(ket) + "]";
		String id = String.valueOf(Helper.user.getId());
		if (id == null) {
			Toast.makeText(context, "请登录后在操作!", 0).show();
			return;
		}
		VolleyRunnableService.saveMonitor(id, bpString, bgString, wtString,
				tmpString, ketString, "0", "5", TAG,
				new VolleyRunnableService.ClientCallback() {

					@Override
					public void onSuccess(Object data) {
						// TODO Auto-generated method stub
						String s = (String) data;
						Toast.makeText(context, s, 0).show();
					}

					@Override
					public void onFailure(String message) {
						// TODO Auto-generated method stub
						Toast.makeText(context, message, 0).show();
					}

					@Override
					public void onError(String e) {
						// TODO Auto-generated method stub
						Toast.makeText(context, e, 0).show();
					}
				});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 监测蓝牙是否打开，没有打开，打开设置dialog
		// 注册监听器

	}

	private BroadcastReceiver searchDevices = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Bundle b = intent.getExtras();
			
			// 显示所有收到的消息及其细节
			
			// 搜索设备时，取得设备的MAC地址
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				Object[] lstName = b.keySet().toArray();
				for (int i = 0; i < lstName.length; i++) {
					String keyName = lstName[i].toString();
					Log.e(keyName, String.valueOf(b.get(keyName)));
					// System.out.println("----"+keyName+"----"+String.valueOf(b.get(keyName)));
				}
				
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				Log.i("lz", "name = " + device.getName() + "");
				System.out.println("=======" + device.getName());
				// 开始判断蓝牙接入设备名称
				if (device.getName() != null) {
				
					// 如果是称
					if (device.getName().contains("WT")&&(getWet==0)) {

						if (mChatService != null)
							mChatService.stop();
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							mChatService.start();
							mChatService.connect(device);
						} catch (Exception e) {
							// TODO: handle exception
							mChatService.stop();
						}
					} else if (device.getName().contains("BC")) {

						if (sugarChatService != null)
							sugarChatService.stop();
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							sugarChatService.start();
							sugarChatService.connect(device);
						} catch (Exception e) {
							// TODO: handle exception
							sugarChatService.stop();
						}

					} else if (device.getName().contains("NIBP")&&(getBlood==0)) {

						if (bloodService != null)
							bloodService.stop();
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							bloodService.start();
							bloodService.connect(device);
						} catch (Exception e) {
							// TODO: handle exception
							bloodService.stop();
						}

					}
				}

			}
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				closeProDialog();
				btAdapt.startDiscovery();
				//openProDialog("正在搜索中，请稍后");
		}
			
		}
	};

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == 1) {
				lin_tag.setVisibility(View.GONE);
				blueAdapter = new BlueChoseAdaoter(context,
						R.layout.item_bluetooth_listview, list);
				listView.setAdapter(blueAdapter);
			} else {
				lin_tag.setVisibility(View.VISIBLE);
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void call() {// 体重
		// TODO Auto-generated method stub
		mChatService.stop();
		ArrayList<WTDeviceDataJar> _ver = MtBuf.m_buf;
		BlueTooth blue = new BlueTooth();
		blue.img = R.drawable.health_tzs;
		blue.unit = "Kg";
		if (_ver.size()!=0) {
			WTDeviceDataJar wtd = _ver.get(0);
			if (wtd != null) {
				blue.val = wtd.m_data;
				blue.type = 0;
				wt.setMonitorDate(strDate);
				wt.setMode(0);
				wt.setWtValue(Double.parseDouble(wtd.m_data.toString()));
				wt.setUnit("Kg");
			}

			System.out.println("==========" + wtd.m_data);
		} else {
			blue.val = "0";
			blue.type = 0;
		}
		
		for(int i=0;i<list.size();i++)
		{
			if(list.get(i).type==0)
			{
				list.remove(i);
			}   			
			
		}	
		
		
		list.add(blue);
		Message msg = new Message();
		msg.what = 1;
		handler.sendMessage(msg);
        getWet=1;
		btAdapt.startDiscovery();

	}

	@Override
	protected void onDestroy() {
		// 确保在activity被手动销毁时线程是安全的。

		this.unregisterReceiver(searchDevices);
		closeProDialog();
		// try {
		// btSocket.close();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// 仪器的辅助service

		// mSugarSerivce.stop();
		// mOrgService.stop();
		// bcService.stop();
		super.onDestroy();
		// android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	public void call1() {// 血压
		// TODO Auto-generated method stub
		bloodService.stop();
		ArrayList<byte[]> _ver = BloodBuf._dataList;
		BlueTooth blue = new BlueTooth();
		blue.img = R.drawable.health_xys;
		blue.unit = "mmHg";
		byte[] b = _ver.get(0);
		if (_ver != null) {
			blue.val = "高压:" + b[1] + "~" + "低压:" + b[2];
			blue.type = 1;
			Integer lp = Integer.valueOf(b[2]);
			Integer hp = Integer.valueOf(b[1]);
			int pu = Integer.valueOf(b[3]);
			bp.setMonitorDate(strDate);
			bp.setMode(0);
			bp.setPulse(pu);
			bp.setLpValue(lp);
			bp.setHpValue(hp);
			bp.setUnit("mmHg");
		} else {
			blue.val = "高压:0~低压:0";
			blue.type = 1;
		}
		
		for(int i=0;i<list.size();i++)
		{
			if(list.get(i).type==1)
			{
				list.remove(i);
			}   			
			
		}	
		
		list.add(blue);
		System.out.println("==========" + _ver);
		Message msg = new Message();
		msg.what = 1;
		handler.sendMessage(msg);
		getBlood=1;
		btAdapt.startDiscovery();
	}

	@Override
	public void call2() {
		// TODO Auto-generated method stub
	}

	@Override
	public void call3() {
		// TODO Auto-generated method stub
	}

	@Override
	public void redis() {
		// TODO Auto-generated method stub
		if (!btAdapt.isEnabled()) {
			Intent intent0 = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivity(intent0);
		} else {
			btAdapt.startDiscovery();

		}

	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		openProDialog("蓝牙连接关闭中");
		
		if (!(btSocket == null)) {
			try {
				mChatService.stop();
				bloodService.stop();
				btSocket.close();
				btSocket = null;
				Thread.sleep(2000);
				btAdapt.cancelDiscovery();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		closeProDialog();
		//t
		finish();
	}

}
